from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UploadImageSerializer
from shortuuid import uuid
import os
from django.conf import settings

# 处理图片
class UploadImageView(APIView):
    def post(self, request):
        serializer = UploadImageSerializer(data=request.data)
        if serializer.is_valid():
            file = serializer.validated_data.get('image')
            #uuid+ 文件后缀
            file_name = uuid() + os.path.splitext(file.name)[-1]
            path = os.path.join(settings.MEDIA_ROOT, file_name)
            try:
                #二进制存储
                with open(path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
            except Exception:
                return Response({ "errno": 1,'message': '上传失败'})
            return Response({
                "errno": 0,
                "data": {
                        # 图片地址/media/abdc.jpg
                        "url": settings.MEDIA_URL + file_name,
                        "alt": file_name,
                        "href": settings.MEDIA_URL + file_name
                    }
            })

        else:
            return Response({
                "errno": 1,
                "message": "参数验证失败",
                "errors": serializer.errors
            }, status=400)



